package com.googlecode.tabletags.views.jsp.ui;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;

import org.apache.struts2.components.Component;

import com.googlecode.tabletags.components.Table;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * @see Table
 */
public class TableTag extends AbstractURLComponentTag {
    protected String pagerCommand;
    protected String pagerValue;

    protected String sortOrder;
    protected String sortName;
    protected String sortValue;
    
    /**
     * @see org.apache.struts2.views.jsp.ComponentTagSupport#getBean(com.opensymphony.xwork2.util.ValueStack, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public Component getBean(ValueStack stack, HttpServletRequest req,
        HttpServletResponse res) {
        Table table = new Table(stack, req, res);
        table.setSortName(sortName);
        table.setSortOrder(sortOrder);
        table.setSortValue(sortValue);
        return table;
    }

    /**
     * @see org.apache.struts2.views.jsp.ComponentTagSupport#doEndTag()
     */
    public int doEndTag() throws JspException {
        component = null;
        return EVAL_PAGE;
    }

    /**
     * @see javax.servlet.jsp.tagext.BodyTagSupport#doAfterBody()
     */
    public int doAfterBody() throws JspException {
        boolean again = component.end(pageContext.getOut(), getBody());

        if(again) {
            return EVAL_BODY_AGAIN;
        } else {
            if(bodyContent != null) {
                try {
                    bodyContent.writeOut(bodyContent.getEnclosingWriter());
                } catch(Exception e) {
                    throw new JspException(e.getMessage());
                }
            }
            return SKIP_BODY;
        }
    }

    /**
     * @see com.opensymphony.webwork.views.jsp.ui.AbstractUITag#populateParams()
     */
    protected void populateParams() {
        super.populateParams();

        Table table = ((Table) component);
        table.setPagerCommand(pagerCommand);
        table.setPagerValue(pagerValue);
        
        table.setSortName(sortName);
        table.setSortOrder(sortOrder);
        table.setSortValue(sortValue);
    }

    public void setSortName(String sortName) {
        this.sortName = sortName;
    }

    public void setSortOrder(String sortOrder) {
        this.sortOrder = sortOrder;
    }

    public void setSortValue(String sortValue) {
        this.sortValue = sortValue;
    }

    public void setPagerCommand(String pagerCommand) {
        this.pagerCommand = pagerCommand;
    }

    public void setPagerValue(String pagerValue) {
        this.pagerValue = pagerValue;
    }
}
